package main

import (
	"cloudWego/kitex_gen/example/shop/item"
	"cloudWego/kitex_gen/example/shop/item/itemservice"
	"cloudWego/kitex_gen/example/shop/stock"
	"cloudWego/kitex_gen/example/shop/stock/stockservice"
	"context"
	"fmt"
	"github.com/kitex-contrib/registry-nacos/v2/resolver"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"time"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/client/callopt"
)

var (
	itemCli  itemservice.Client
	stockCli stockservice.Client
)

func main() {

	// nacos 服务发现
	sc := []constant.ServerConfig{
		*constant.NewServerConfig("192.168.8.140", 8848),
	}
	cc := constant.ClientConfig{
		NamespaceId:         "go-zero1",
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "info",
		Username:            "nacos",
		Password:            "nacos",
	}

	nacoscli, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
	if err != nil {
		panic(err)
	}

	// item 服务发现
	itemcli, err := itemservice.NewClient("item", client.WithResolver(resolver.NewNacosResolver(nacoscli)))
	if err != nil {
		panic(err)
	}
	itemCli = itemcli

	// stock 服务发现
	stockcli, err := stockservice.NewClient("stock", client.WithResolver(resolver.NewNacosResolver(nacoscli)))
	if err != nil {
		panic(err)
	}
	stockCli = stockcli

	//c, err := itemservice.NewClient("example.shop.item", client.WithHostPorts("0.0.0.0:8888"))
	//if err != nil {
	//	log.Fatal(err)
	//}
	//cli = itemCli

	hz := server.New(server.WithHostPorts("0.0.0.0:8088"))

	hz.GET("/api/item/get", Handler)
	hz.GET("/api/stock/get", Handler2)

	if err := hz.Run(); err != nil {
		//log.Fatal(err)
		fmt.Println(666666666666)
	}
}

func Handler(ctx context.Context, c *app.RequestContext) {
	req := item.NewGetItemReq()
	req.Id = 1024
	resp, err := itemCli.GetItem(context.Background(), req, callopt.WithRPCTimeout(3*time.Second))
	if err != nil {
		//log.Fatal(err)
		//c.String(500, fmt.Sprintf("请求 stock 服务失败：%s", err.Error()))
		c.JSON(500, fmt.Sprintf("请求 stock 服务失败：%s", err.Error()))
	}

	//c.String(200, resp.String())
	c.JSON(200, resp)
}

func Handler2(ctx context.Context, c *app.RequestContext) {
	req := stock.NewGetItemStockReq()
	req.ItemId = 1024
	resp, err := stockCli.GetItemStock(context.Background(), req, callopt.WithRPCTimeout(3*time.Second))
	if err != nil {
		//log.Fatal(err)
		//c.String(500, fmt.Sprintf("请求 stock 服务失败：%s", err.Error()))
		c.JSON(500, fmt.Sprintf("请求 stock 服务失败：%s", err.Error()))
	}

	//c.String(200, resp.String())
	c.JSON(200, resp)
}
